package com.softeware.control;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;
import java.util.Hashtable;

@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
    private ServletContext application;
    Hashtable<String,String> users;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        application = getServletContext();

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        buildMap();

        if(checkLogin(username,password,response)){
            request.getSession().setAttribute("username",username);
            request.getRequestDispatcher("main.jsp").forward(request,response);
        }else {
            request.getRequestDispatcher("Login.jsp?info=unLogin&key="+ users.size()).forward(request,response);
        }
    }

    private boolean checkLogin(String username, String password,HttpServletResponse response) throws IOException {
        if(users.containsKey(username)) {
//            return true;
            return users.get(username).equals(password);
        }
        return false;
    }

    private void buildMap() {
        users = (Hashtable<String, String>) application.getAttribute("users");
        if (users == null) {
            users = new Hashtable<>();
            application.setAttribute("users", users);
        }
    }
}